import axios, { type AxiosRequestConfig, type Canceler } from "axios";
function generateReqKey(config: AxiosRequestConfig) {
    const { method, url, params, data } = config;
    return [method, url, JSON.stringify(params), JSON.stringify(data)].join("&");
}

class YcAxiosCancel {
    pendingRequest = new Map<string, Canceler>();
    addPendingRequest(config: AxiosRequestConfig) {
        const requestKey = generateReqKey(config);
        config.cancelToken = config.cancelToken || new axios.CancelToken((cancel) => {
            if (!this.pendingRequest.has(requestKey)) {
                this.pendingRequest.set(requestKey, cancel);
            }
        });
    }
    removePendingRequest(config: AxiosRequestConfig) {
        const requestKey = generateReqKey(config);
        if (this.pendingRequest.has(requestKey)) {
            const cancelToken = this.pendingRequest.get(requestKey)!!;
            cancelToken(requestKey);
            this.pendingRequest.delete(requestKey);
        }
    }
    /**
     * 添加重复请求拦截器
     */
    test() {
        axios.interceptors.request.use((config: AxiosRequestConfig) => {
            this.removePendingRequest(config); // 检查是否存在重复请求，若存在则取消已发的请求
            this.addPendingRequest(config); // 把当前请求信息添加到pendingRequest对象中
            return config;
        }, (error) => {
            return Promise.reject(error);
        });
        axios.interceptors.response.use((response) => {
            this.removePendingRequest(response.config); // 从pendingRequest对象中移除请求
            return response;
        }, (error) => {
            this.removePendingRequest(error.config || {}); // 从pendingRequest对象中移除请求
            if (axios.isCancel(error)) {
                console.log("已取消的重复请求：" + error.message);
            } else {
                // 添加异常处理
            }
            return Promise.reject(error);
        });
    }
}